package stutter.client;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringReader;

import stutter.shared.FieldVerifier;
import com.google.gwt.core.client.EntryPoint;
import com.google.gwt.core.client.GWT;
import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.event.dom.client.KeyCodes;
import com.google.gwt.event.dom.client.KeyUpEvent;
import com.google.gwt.event.dom.client.KeyUpHandler;
import com.google.gwt.user.client.rpc.AsyncCallback;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.DialogBox;
import com.google.gwt.user.client.ui.HTML;
import com.google.gwt.user.client.ui.Label;
import com.google.gwt.user.client.ui.RootPanel;
import com.google.gwt.user.client.ui.TextArea;
import com.google.gwt.user.client.ui.VerticalPanel;

/**
 * Entry point classes define <code>onModuleLoad()</code>.
 */
public class Stutter_web_app implements EntryPoint {
	/**
	 * The message displayed to the user when the server cannot be reached or
	 * returns an error.
	 */
	private static final String SERVER_ERROR = "An error occurred while "
			+ "attempting to contact the server. Please check your network "
			+ "connection and try again.";

	/**
	 * Create a remote service proxy to talk to the server-side Greeting service.
	 */
	private final GreetingServiceAsync greetingService = GWT
			.create(GreetingService.class);

	/**
	 * This is the entry point method.
	 */
	public void onModuleLoad() {
		final Button sendButton = new Button("Send");
		final TextArea nameField = new TextArea();
		nameField.setWidth("350");
		nameField.setHeight("350");
		nameField.setText("GWT User");
		final Label errorLabel = new Label();

		// We can add style names to widgets
		sendButton.addStyleName("sendButton");

		// Add the nameField and sendButton to the RootPanel
		// Use RootPanel.get() to get the entire body element
		RootPanel.get("nameFieldContainer").add(nameField);
		RootPanel.get("sendButtonContainer").add(sendButton);
		RootPanel.get("errorLabelContainer").add(errorLabel);

		// Focus the cursor on the name field when the app loads
		nameField.setFocus(true);
		nameField.selectAll();

		// Create the popup dialog box
		final DialogBox dialogBox = new DialogBox();
		dialogBox.setText("Remote Procedure Call");
		dialogBox.setAnimationEnabled(true);
		final Button closeButton = new Button("Close");
		// We can set the id of a widget by accessing its Element
		closeButton.getElement().setId("closeButton");
		final Label textToServerLabel = new Label();
		final HTML serverResponseLabel = new HTML();
		VerticalPanel dialogVPanel = new VerticalPanel();
		dialogVPanel.addStyleName("dialogVPanel");
		dialogVPanel.add(new HTML("<b>Sending name to the server:</b>"));
		dialogVPanel.add(textToServerLabel);
		dialogVPanel.add(new HTML("<br><b>Server replies:</b>"));
		dialogVPanel.add(serverResponseLabel);
		dialogVPanel.setHorizontalAlignment(VerticalPanel.ALIGN_RIGHT);
		dialogVPanel.add(closeButton);
		dialogBox.setWidget(dialogVPanel);

		// Add a handler to close the DialogBox
		closeButton.addClickHandler(new ClickHandler() {
			public void onClick(ClickEvent event) {
				dialogBox.hide();
				sendButton.setEnabled(true);
				sendButton.setFocus(true);
			}
		});

		// Create a handler for the sendButton and nameField
		class MyHandler implements ClickHandler {
			/**
			 * Fired when the user clicks on the sendButton.
			 */
			public void onClick(ClickEvent event) {
				//save one copy for the end
			  String displayInputText = nameField.getText();
			  String inputText = nameField.getText();
			  //string previousWord will be used to store the previous word in the file
			  String previousWord = "";
			  //int nLine will store the line you are currently on
			  int nLine = 0;
			  //output string will save the end result
			  String outputString = "";
			  //split on new line to get the different lines\
				for (String fileString : inputText.split("\\r\\n")) {
				  nLine++;
				  for (String currentWord : fileString.split(" ")) {
				    //if currentWord and previousWord are the same output a statement
				    if (isSame(removeSpecialCharacters(previousWord), removeSpecialCharacters(currentWord)) > 0) {
					  outputString = outputString + "Repeated word on line ";
					  outputString = outputString + nLine;
					  outputString = outputString + ": ";
					  outputString = outputString + removeSpecialCharacters(previousWord);
					  outputString = outputString + " ";
					  outputString = outputString + removeSpecialCharacters(currentWord);
					  outputString = outputString + "<br>";
			        }
			        //previousWord becomes the current word
			        previousWord = currentWord;
			      }
			    }
			  //output results
			  dialogBox.setText("Results:");
			  textToServerLabel.setText(displayInputText);
			  serverResponseLabel.setHTML(outputString);
			  dialogBox.center();
			  closeButton.setFocus(true);
			}

			/**
			 * Send the name from the nameField to the server and wait for a response.
			 */
			private void sendNameToServer() {
				// First, we validate the input.
				errorLabel.setText("");
				String textToServer = nameField.getText();
				if (!FieldVerifier.isValidName(textToServer)) {
					errorLabel.setText("Please enter at least four characters");
					return;
				}

				// Then, we send the input to the server.
				sendButton.setEnabled(false);
				textToServerLabel.setText(textToServer);
				serverResponseLabel.setText("");
				greetingService.greetServer(textToServer,
						new AsyncCallback<String>() {
							public void onFailure(Throwable caught) {
								// Show the RPC error message to the user
								dialogBox
										.setText("Remote Procedure Call - Failure");
								serverResponseLabel
										.addStyleName("serverResponseLabelError");
								serverResponseLabel.setHTML(SERVER_ERROR);
								dialogBox.center();
								closeButton.setFocus(true);
							}

							public void onSuccess(String result) {
								dialogBox.setText("Remote Procedure Call");
								serverResponseLabel
										.removeStyleName("serverResponseLabelError");
								serverResponseLabel.setHTML(result);
								dialogBox.center();
								closeButton.setFocus(true);
							}
						});
			}
		}

		// Add a handler to send the name to the server
		MyHandler handler = new MyHandler();
		sendButton.addClickHandler(handler);
	}
	
		  /* 
		   * Return string without any special characters
		   * Special characters are in deleteStrings array
		   * 
		   * @param inputString original string that may contain special characters 
		   * @return string without special characters 
		  */
		  public static String removeSpecialCharacters(String inputString) {
		    String[] deleteStrings = "\0,\n, ,  ,\\.,!,-,\\+,=,;,:,\\?,\\&,\\{,\\},\\\\".split(",");
		    //replace each character with ""
		    for (int i = 0; i < deleteStrings.length; i++) {
		      String currentChar = deleteStrings[i];
		      inputString = inputString.replaceAll(currentChar, "");
			}
		    //replace all commas too (this was causing an error with the split function)
		    inputString = inputString.replaceAll(",", "");
		    return inputString;
		  }
	
		  /* 
		   * Return 1 or 0 when two input strings are the same
		   * 
		   * @param firstString string to test
		   * @param secondString string to test
		   * @return 1 if the strings are the same and 0 if the strings are different
		  */
		  public static int isSame(String firstString, String secondString) {
			//convert to character arrays
		    char[] firstArray = firstString.toUpperCase().toCharArray();
		    char[] secondArray = secondString.toUpperCase().toCharArray();
		    
		    //int i servers as the index of the array
		    int i = 0;    
		    //if two characters don't match return 0 (false)
		    while (i < firstArray.length && i < secondArray.length) {
		      if (firstArray[i] != secondArray[i]) {
		    	return 0;
		      }
		      i++;
		    }
		    //if the lengths and i are not the same then the words are not the same
		    if (i == firstArray.length && i == secondArray.length) {
		      return 1;
		    } else {
		      return 0;
		    }
		  }
}
